package top.mybatisx.mpquery.toolkit;

import top.mybatisx.sql.core.toolkit.ChkUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * sql辅助处理工具类
 */
public class SqlUtil {

    // 计算占位符个数
    public static int countQuestionMarks(String sql) {
        char questionMark = '?';
        int count = 0;

        for (int i = 0; i < sql.length(); i++) {
            if (sql.charAt(i) == questionMark) {
                count++;
            }
        }
        return count;
    }

    // 用占位符 #{p0} #{p1} ...... 代替 ?
    public static String handleMeta(String sql) {
        StringBuilder sb = new StringBuilder();
        int index = 0;
        for (int i = 0; i < sql.length(); i++) {
            char currentChar = sql.charAt(i);
            if (currentChar == '?') {
                sb.append("#{p" + index + "}");
                index++;
            } else {
                sb.append(currentChar);
            }
        }
        return sb.toString();
    }

    // 转为占位符格式
    public static Map<String, Object> turnParamsToMap(List<Object> values) {
        if (ChkUtil.isNull(values)) return null;
        Map<String, Object> params = new HashMap<>();
        int i = 0;
        for (Object value : values) {
            params.put("p" + i, value);
            i++;
        }
        return params;
    }
}
